import json
import time
import uuid
from datetime import datetime
from sqlalchemy import or_, and_
from Model.default import get_db
from Model.mysocketio.info import Double_Room, Group_Room
from Model.user.User import user_expand
from api.mysocketio.update_room_info import update_userinfo_to_room



def deal_create_group_room(user_ids,created_user):
    db = get_db()
    max_retries = 3  # 最大重试次数
    retry_delay = 1  # 重试间隔（秒）
    try:
        now = str(datetime.now())
        room_id = str(uuid.uuid4())

        for attempt in range(max_retries):
            all_success = True  # 假设本次尝试全部成功
            for user_id in user_ids:
                # 传入db使用同一个上下文便于全部回滚
                success = update_userinfo_to_room(room_id, user_id, 'joined_at', now,'group',db)
                if not success:
                    all_success = False
                    print(f"用户 {user_id} 更新失败，第 {attempt + 1} 次重试...")
                    break
            if all_success:
                break
            if attempt < max_retries - 1:
                time.sleep(retry_delay)

        if  not  (all_success and deal_user_friends_info_group(db,user_ids)):
            raise Exception("部分用户更新失败/状态错误，无法创建群组")

        room_to_user = {
            str(user_id): {"joined_at": now, "active": 1}
            for user_id in user_ids
        }
        new_room = Group_Room(
            room_id=room_id,
            created_at=now,
            is_active=True,
            user_info=json.dumps(room_to_user),
            created_user=created_user
        )
        db.add(new_room)
        db.commit()
        return True
    except Exception as e:
        db.rollback()
        print(f"创建群组失败: {e}")
        return False
    finally:
        db.close()

def deal_create_middle_room(user_id):
    now = str(datetime.now())
    pass



def deal_user_friends_info_double(db,user_id):
    try:
        # 先暂时只处理id
        one = user_id[0]
        another = user_id[1]
        userinfo1=db.query(user_expand).filter_by(id=one).first()
        userinfo1.user_key.friends_count+=1
        middle1=json.loads(userinfo1.friends_info or json.dumps({}))
        middle1.setdefault(another,{}).setdefault(another,{})
        userinfo1.friends_info = json.dumps(middle1)
        userinfo2=db.query(user_expand).filter_by(id=another).first()
        userinfo2.user_key.friends_count += 1
        middle2=json.loads(userinfo2.friends_info or json.dumps({}))
        middle2.setdefault(one,{}).setdefault(one,{})
        userinfo2.friends_info = json.dumps(middle2)
        return  True
        #不提交,统一处理
    except Exception as e:
        print(e)
        return False
    finally:
        pass


def deal_user_friends_info_group(db, user_ids):
    """
    批量更新用户好友计数 (friends_count)，但不提交事务
    :param db: 数据库会话
    :param user_ids: 需要更新的用户ID列表
    :return: bool 表示操作是否成功
    """
    try:
        # 查询所有涉及的用户扩展信息
        userinfo_list = db.query(user_expand).filter(user_expand.id.in_(user_ids)).all()
        # 批量更新好友计数
        for userinfo in userinfo_list:
            userinfo.user_key.groups_count += 1
        # 不提交事务，让调用方处理
        return True
    except Exception as e:
        db.rollback()  # 如果出现异常，回滚事务
        print(f"批量更新好友计数失败: {e}")
        return False


def deal_create_double_room(user_id,created_user):
    db = get_db()
    try:
        one=user_id[0]
        another=user_id[1]
        if db.query(Double_Room).filter(
                        or_(
                            and_(Double_Room.one ==one, Double_Room.another ==another),
                            and_(Double_Room.one==another, Double_Room.another==one)
                            )
                    ).limit(1).first():
            # 避免重复创建
            return False
        now = str(datetime.now())
        room_id = str(uuid.uuid4())
        new_room = Double_Room(
            room_id=room_id,
            created_at=now,
            is_active=True,
            one=one,
            another=another
        )

        # 更新用户的信息, 私聊实际上是没有必要的,只是为了拓展性
        judge1=update_userinfo_to_room(room_id, one, 'joined_at', now, 'double')
        judge2=update_userinfo_to_room(room_id, another, 'joined_at', now, 'double')
        judge3=deal_user_friends_info_double(db,user_id)
        if judge1 and judge2 and judge3:
            db.add(new_room)
            db.commit()
            return True
        else:
            db.rollback()
            return False

    except Exception as e:
        print(0)
        db.rollback()
        return False
    finally:
        db.close()



ROOM_MAPPER={
    'group':deal_create_group_room,
    'middle':deal_create_middle_room,
    'double':deal_create_double_room,
}

# 主程序
def create_room(user_id,type,created_user):
    try:
       return ROOM_MAPPER.get(type,deal_create_middle_room)(user_id,created_user)
    except Exception as e:
        pass


